package net.oschina.aibinxiao.security.dsa;

import org.apache.commons.codec.binary.Hex;

import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Author: AiBinXiao
 * @Description: 数字签名算法DSA
 * @Date: 2017/10/14 9:11
 */

public class MyDSA {
    private static String src = "imooc security dsa";

    public static void main(String[] args) {
        jdkDSA();
    }

    // JDK实现的DSA
    public static void jdkDSA() {
        try {
            // 1.初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
            keyPairGenerator.initialize(512);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
            DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate();

            // 2.执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded()); //私钥进行签名
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(privateKey);
            signature.update(src.getBytes());
            byte[] result = signature.sign();
            System.out.println("JDK DSA sign : " + Hex.encodeHexString(result));
            // JDK DSA sign : 302c0214696014597db57470a3ce393df3daf51dfedc300b02147569db7ecc96a9b970379ffe56900e27a9b2263a

            // 3.验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("DSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            Boolean bool = signature.verify(result);
            System.out.println("JDK DSA verify : " + bool);
            // JDK DSA verify : true
        } catch (Exception e) {

        }
    }

}
